from rest_framework import serializers
from django.contrib.auth.models import User
from .models import Template, ProcessingTask, UploadedFile, SystemLog, FieldConfig, ProcessingRule, DataSourceConfig, OutputConfig


class UserSerializer(serializers.ModelSerializer):
    """用户序列化器"""
    class Meta:
        model = User
        fields = ['id', 'username', 'first_name', 'last_name', 'email']
        read_only_fields = ['id']


class FieldConfigSerializer(serializers.ModelSerializer):
    """字段配置序列化器"""
    class Meta:
        model = FieldConfig
        fields = ['id', 'field_name', 'source_column', 'rule_type', 'config_data']


class ProcessingRuleSerializer(serializers.ModelSerializer):
    """处理规则序列化器"""
    class Meta:
        model = ProcessingRule
        fields = ['id', 'rule_name', 'rule_order', 'rule_type', 'rule_config', 'condition_config', 'is_active']


class DataSourceConfigSerializer(serializers.ModelSerializer):
    """数据源配置序列化器"""
    class Meta:
        model = DataSourceConfig
        fields = ['id', 'source_name', 'source_order', 'source_type', 'read_direction', 'data_range', 'header_config', 'join_keys', 'filter_conditions']


class OutputConfigSerializer(serializers.ModelSerializer):
    """输出配置序列化器"""
    class Meta:
        model = OutputConfig
        fields = ['id', 'output_name', 'output_type', 'output_format', 'output_config', 'filename_template']


class TemplateSerializer(serializers.ModelSerializer):
    """模板序列化器"""
    created_by = UserSerializer(read_only=True)
    field_configs_rel = FieldConfigSerializer(many=True, read_only=True)
    processing_rules = ProcessingRuleSerializer(many=True, read_only=True)
    data_sources = DataSourceConfigSerializer(many=True, read_only=True)
    output_configs = OutputConfigSerializer(many=True, read_only=True)
    
    class Meta:
        model = Template
        fields = [
            'id', 'name', 'description', 'is_active', 'template_file',
            'template_type', 'data_source_type', 'excel_structure', 'field_configs',
            'multi_file_config', 'processing_logic', 'output_config',
            'mapping_config', 'fixed_config', 'pol_config', 'shipper_config',
            'created_at', 'updated_at', 'created_by',
            'field_configs_rel', 'processing_rules', 'data_sources', 'output_configs'
        ]
        read_only_fields = ['id', 'created_at', 'updated_at', 'created_by',
                            'field_configs', 'processing_logic', 'output_config']
    
    def validate_name(self, value):
        """验证模板名称唯一性"""
        if self.instance:
            # 更新时排除当前实例
            if Template.objects.exclude(id=self.instance.id).filter(name=value).exists():
                raise serializers.ValidationError("模板名称已存在")
        else:
            # 创建时检查唯一性
            if Template.objects.filter(name=value).exists():
                raise serializers.ValidationError("模板名称已存在")
        return value


class TemplateListSerializer(serializers.ModelSerializer):
    """模板列表序列化器（简化版）"""
    created_by_name = serializers.CharField(source='created_by.username', read_only=True)
    
    class Meta:
        model = Template
        fields = [
            'id', 'name', 'description', 'is_active',
            'created_at', 'updated_at', 'created_by_name'
        ]
        read_only_fields = ['id', 'created_at', 'updated_at']


class ProcessingTaskSerializer(serializers.ModelSerializer):
    """处理任务序列化器"""
    created_by = UserSerializer(read_only=True)
    template = TemplateListSerializer(read_only=True)
    template_id = serializers.UUIDField(write_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    duration = serializers.SerializerMethodField()
    
    class Meta:
        model = ProcessingTask
        fields = [
            'id', 'task_name', 'status', 'status_display', 'template', 'template_id',
            'result_message', 'error_message', 'started_at', 'completed_at',
            'result_file', 'created_at', 'updated_at', 'created_by',
            'duration'
        ]
        read_only_fields = [
            'id', 'created_at', 'updated_at', 'created_by',
            'started_at', 'completed_at'
        ]
    
    def get_duration(self, obj):
        """获取任务执行时长"""
        if obj.started_at and obj.completed_at:
            return (obj.completed_at - obj.started_at).total_seconds()
        return None
    
    def validate_template_id(self, value):
        """验证模板ID"""
        try:
            template = Template.objects.get(id=value)
            if not template.is_active:
                raise serializers.ValidationError("所选模板未激活")
            return value
        except Template.DoesNotExist:
            raise serializers.ValidationError("模板不存在")


class ProcessingTaskListSerializer(serializers.ModelSerializer):
    """处理任务列表序列化器（简化版）"""
    template_name = serializers.CharField(source='template.name', read_only=True)
    created_by_name = serializers.CharField(source='created_by.username', read_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    
    class Meta:
        model = ProcessingTask
        fields = [
            'id', 'task_name', 'status', 'status_display',
            'template_name', 'created_by_name', 'created_at', 'completed_at'
        ]
        read_only_fields = ['id', 'created_at', 'completed_at']


class UploadedFileSerializer(serializers.ModelSerializer):
    """上传文件序列化器"""
    created_by = UserSerializer(read_only=True)
    file_type_display = serializers.CharField(source='get_file_type_display', read_only=True)
    file_size_mb = serializers.SerializerMethodField()
    file_url = serializers.SerializerMethodField()
    
    class Meta:
        model = UploadedFile
        fields = [
            'id', 'original_name', 'file', 'file_url', 'file_type', 'file_type_display',
            'file_size', 'file_size_mb', 'task', 'template',
            'created_at', 'updated_at', 'created_by'
        ]
        read_only_fields = ['id', 'created_at', 'updated_at', 'created_by', 'file_size']
    
    def get_file_size_mb(self, obj):
        """获取文件大小（MB）"""
        return round(obj.file_size / (1024 * 1024), 2) if obj.file_size else 0
    
    def get_file_url(self, obj):
        """获取文件URL"""
        if obj.file:
            request = self.context.get('request')
            if request:
                return request.build_absolute_uri(obj.file.url)
            return obj.file.url
        return None
    
    def validate_file(self, value):
        """验证文件"""
        # 检查文件大小（50MB限制）
        if value.size > 50 * 1024 * 1024:
            raise serializers.ValidationError("文件大小不能超过50MB")
        
        # 检查文件扩展名
        allowed_extensions = ['.xlsx', '.xls', '.csv', '.txt']
        file_extension = value.name.lower().split('.')[-1]
        if f'.{file_extension}' not in allowed_extensions:
            raise serializers.ValidationError(
                f"不支持的文件格式。支持的格式：{', '.join(allowed_extensions)}"
            )
        
        return value
    
    def create(self, validated_data):
        """创建文件记录时自动设置文件大小"""
        file = validated_data.get('file')
        if file:
            validated_data['file_size'] = file.size
        return super().create(validated_data)


class SystemLogSerializer(serializers.ModelSerializer):
    """系统日志序列化器"""
    level_display = serializers.CharField(source='get_level_display', read_only=True)
    task_name = serializers.CharField(source='task.task_name', read_only=True)
    created_by = UserSerializer(read_only=True)
    
    class Meta:
        model = SystemLog
        fields = [
            'id', 'level', 'level_display', 'message', 'module', 'function',
            'task', 'task_name', 'created_at', 'created_by'
        ]
        read_only_fields = ['id', 'created_at', 'created_by']


class SystemLogListSerializer(serializers.ModelSerializer):
    """系统日志列表序列化器（简化版）"""
    level_display = serializers.CharField(source='get_level_display', read_only=True)
    
    class Meta:
        model = SystemLog
        fields = [
            'id', 'level', 'level_display', 'message', 'module', 'created_at'
        ]
        read_only_fields = ['id', 'created_at']


# 用于文件上传的特殊序列化器
class FileUploadSerializer(serializers.Serializer):
    """文件上传序列化器"""
    files = serializers.ListField(
        child=serializers.FileField(),
        allow_empty=False,
        help_text="要上传的文件列表"
    )
    file_type = serializers.ChoiceField(
        choices=UploadedFile.FILE_TYPE_CHOICES,
        default='source',
        help_text="文件类型"
    )
    task_id = serializers.UUIDField(
        required=False,
        allow_null=True,
        help_text="关联的任务ID（可选）"
    )
    template_id = serializers.UUIDField(
        required=False,
        allow_null=True,
        help_text="关联的模板ID（可选）"
    )
    
    def validate_files(self, value):
        """验证文件列表"""
        if len(value) > 10:
            raise serializers.ValidationError("一次最多只能上传10个文件")
        
        total_size = sum(file.size for file in value)
        if total_size > 200 * 1024 * 1024:  # 200MB
            raise serializers.ValidationError("文件总大小不能超过200MB")
        
        return value
    
    def validate_task_id(self, value):
        """验证任务ID"""
        if value:
            try:
                ProcessingTask.objects.get(id=value)
            except ProcessingTask.DoesNotExist:
                raise serializers.ValidationError("任务不存在")
        return value
    
    def validate_template_id(self, value):
        """验证模板ID"""
        if value:
            try:
                Template.objects.get(id=value)
            except Template.DoesNotExist:
                raise serializers.ValidationError("模板不存在")
        return value